<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import EditForm from '@/views/Article/Edit.vue'
import type { ElMessage, ElMessageBox } from 'element-plus'
import {
  articlePage,
  articleBatchDelete,
  articleRemoveById,
  getListByAccountName,
  getListBySource
} from '@/apis/article.js'
import { getListByParentCode } from '@/apis/sysdict.js'

const instance = getCurrentInstance()
let searchEntity = reactive({
  title: '',
  category: null,
  auditState: null,
  articleState: null,
  accountName: null,
  istop: null,
  date: [],
  state: -1,
  source: '',
  keyword: ''
})
let searchForm = ref()
let searchFormItem = ref()
let more = reactive({ state: false, icon: 'ArrowDown', text: '展开' })
let tableData = reactive({
  current: 1,
  size: 10,
  total: 0,
  pages: 0,
  records: []
})

let selected = ref([])

function selectionChange(selection) {
  selected.value = selection
}

function handleSizeChange(size) {
  tableData.size = size
  getPage()
}

function handleCurrentChange(current) {
  tableData.current = current
  getPage()
}

function resetForm() {
  if (!searchForm) return
  searchForm.value.resetFields()
}
function showMore() {
  if (more.state) {
    searchFormItem.value.style.height = '52px'
    more.state = false
    more.text = '展开'
    more.icon = 'ArrowDown'
  } else {
    searchFormItem.value.style.height = '100%'
    more.state = true
    more.icon = 'ArrowUp'
    more.text = '收起'
  }
  instance.ctx.$forceUpdate()
}

let editfrom = ref()

function handleEdit(no) {
  editfrom.value.open(no)
}

function getIndex(index) {
  return (tableData.current - 1) * tableData.size + index + 1
}

function getPage() {
  articlePage({
    page: tableData.current,
    size: tableData.size,
    title: searchEntity.title,
    category: searchEntity.category,
    auditState: searchEntity.auditState,
    articleState: searchEntity.articleState,
    accountName: searchEntity.accountName,
    istop: searchEntity.istop,
    date: searchEntity.date,
    state: searchEntity.state,
    keyword: searchEntity.keyword
  })
    .then((res) => {
      tableData.current = res.current
      tableData.size = res.size
      tableData.total = res.total
      tableData.pages = res.pages
      tableData.records = res.records
    })
    .catch((error) => {
      console.log(error)
    })
}

let categoryList = ref([])

function getCategoryList(category) {
  categoryList.value = []

  getListByParentCode(category)
    .then((response) => {
      response.forEach((element) => {
        categoryList.value.push({ value: element.code, label: element.name })
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

function batchDelete() {
  ElMessageBox.confirm('确定要删除 ' + selected.value.length + ' 条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      articleBatchDelete(selected.value.map((elem) => elem.no))
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

function handleDelete(no) {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      articleRemoveById(no)
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
/**
 * auditState 审核状态  1 审核通过  0 审核驳回
 * articleState 文章状态  1 发布  0 暂存
 * issueTime 发布时间
 */
function getState(auditState, articleState, issueTime) {
  //当前时间戳
  let datetime = new Date().getTime()
  //发布时间戳
  let issuetime = Date.parse(new Date(issueTime))
  if (auditState == null) {
    return '<span style="color:#E6A23C;">待审核</span>'
  } else if (auditState == 0) {
    return '<span style="color:red;">审核驳回</span>'
  } else if (articleState == 0) {
    return '<span style="color:#E6A23C;">待审核</span>'
  } else if (articleState == 1 && datetime >= issuetime) {
    return '<span style="color:green;">已发布</span>'
  } else if (articleState == 1 && datetime < issuetime) {
    return '<span>待发布</span>'
  }
}

const accountloading = ref(false)
interface ListItem {
  value: string
  label: string
}
const accountNameList = ref<ListItem[]>([])

const accountremoteMethod = (query: string) => {
  if (query) {
    accountloading.value = true
    accountNameList.value = []

    getListByAccountName(query)
      .then((response) => {
        accountloading.value = false
        response.forEach((element) => {
          accountNameList.value.push({ value: element.accountName, label: element.accountName })
        })
      })
      .catch((error) => {
        console.log(error)
      })
  } else {
    accountNameList.value = []
  }
}

const sourceloading = ref(false)

const sourceList = ref<ListItem[]>([])

const sourceremoteMethod = (query: string) => {
  if (query) {
    sourceloading.value = true
    sourceList.value = []

    getListBySource(query)
      .then((response) => {
        sourceloading.value = false
        response.forEach((element) => {
          sourceList.value.push({ value: element.source, label: element.source })
        })
      })
      .catch((error) => {
        console.log(error)
      })
  } else {
    sourceList.value = []
  }
}

onMounted(() => {
  getPage()

  getCategoryList('ArticleCategroy')
})
</script>

<template>
  <el-card class="searchForm" header="查询条件" shadow="never">
    <template #header>
      <div class="card-header">
        <el-icon style="color: rgb(12 43 77)" size="18"><Operation /></el-icon>
        <h1>查询条件</h1>
      </div>
    </template>
    <el-form inline :model="searchEntity" label-width="70px" ref="searchForm">
      <div ref="searchFormItem" style="height: 52px; overflow: hidden">
        <el-form-item label="标题" prop="title">
          <el-input v-model="searchEntity.title" placeholder="标题"> </el-input>
        </el-form-item>
        <el-form-item label="所属栏目" prop="category">
          <el-select-v2
            v-model="searchEntity.category"
            :options="categoryList"
            placeholder="所属栏目"
          ></el-select-v2>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select-v2
            v-model="searchEntity.state"
            :options="[
              { value: 1, label: '已发布' },
              { value: 0, label: '待发布' },
              { value: -1, label: '待审核' },
              { value: -2, label: '审核驳回' }
            ]"
            placeholder="发布状态"
          ></el-select-v2>
        </el-form-item>
        <el-form-item label="发布人" prop="accountName">
          <el-select
            v-model="searchEntity.accountName"
            filterable
            remote
            reserve-keyword
            placeholder="发布人"
            :remote-method="accountremoteMethod"
            :loading="accountloading"
          >
            <el-option
              v-for="item in accountNameList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否置顶" prop="istop">
          <el-select-v2
            v-model="searchEntity.istop"
            :options="[
              { value: 1, label: '是' },
              { value: 0, label: '否' }
            ]"
            placeholder="是否置顶"
          ></el-select-v2>
        </el-form-item>
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="searchEntity.keyword" placeholder="关键词"> </el-input>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-select
            v-model="searchEntity.source"
            filterable
            remote
            reserve-keyword
            placeholder="来源"
            :remote-method="sourceremoteMethod"
            :loading="sourceloading"
          >
            <el-option
              v-for="item in sourceList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="date">
          <el-date-picker
            v-model="searchEntity.date"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </div>

      <el-row style="justify-content: center">
        <el-button type="primary" auto-insert-space icon="Search" @click="getPage">搜索</el-button>
        <el-button auto-insert-space icon="CircleClose" @click="resetForm">重置</el-button>
        <el-button type="primary" link @click="showMore"
          >{{ more.text
          }}<el-icon class="el-icon--right"><component :is="more.icon"></component></el-icon
        ></el-button>
      </el-row>
    </el-form>
  </el-card>

  <div class="dataTable">
    <el-row class="tableBtn">
      <!-- <el-button-group class="ml-4"> -->
      <!-- <el-button
        type="primary"
        icon="CirclePlus"
        auto-insert-space
        @click="handleEdit(null)"
        v-has="'article:add'"
        >新增</el-button
      > -->

      <el-button
        type="danger"
        icon="Delete"
        auto-insert-space
        :disabled="!selected.length"
        @click="batchDelete"
        v-has="'article:del'"
        >删除</el-button
      >

      <!-- <el-button type="warning" icon="Download" auto-insert-space>导出</el-button> -->
      <!-- </el-button-group> -->
    </el-row>
    <el-row>
      <el-table
        :data="tableData.records"
        border
        stripe
        max-height="550"
        size="small"
        fit
        @selection-change="selectionChange"
        :header-cell-style="tableHeaderStyle"
        show-overflow-tooltip
      >
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center">
          <template #default="scope">
            <span v-text="getIndex(scope.$index)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column
          prop="categoryName"
          label="所属栏目"
          width="80"
          align="center"
        ></el-table-column>
        <!-- <el-table-column prop="auditState" label="审核结果" width="80" align="center">
          <template #default="scope">
            <span v-if="scope.row.auditState == 1">审核通过</span>
            <span v-if="scope.row.auditState == 0">审核驳回</span>
          </template>
        </el-table-column> -->

        <!-- <el-table-column prop="articleState" label="发布状态" width="80" align="center">
          <template #default="scope">
            <span v-if="scope.row.articleState == 1">发布</span>
            <span v-if="scope.row.articleState == 0">暂存</span>
          </template>
        </el-table-column> -->

        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <span
              v-html="getState(scope.row.auditState, scope.row.articleState, scope.row.issueTime)"
            ></span>
          </template>
        </el-table-column>

        <el-table-column
          prop="issueTime"
          label="发布时间"
          width="150"
          align="center"
          sortable
        ></el-table-column>

        <el-table-column
          prop="editTime"
          label="编辑时间"
          width="150"
          align="center"
          sortable
        ></el-table-column>

        <el-table-column
          prop="accountName"
          label="发布人"
          width="120"
          align="center"
        ></el-table-column>

        <el-table-column prop="istop" label="是否置顶" width="80" align="center">
          <template #default="scope">
            <span v-if="scope.row.istop == 1">是</span>
            <span v-if="scope.row.istop == 0">否</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="180"
          v-has="['article:edit', 'article:del']"
          fixed="right"
        >
          <template #header>操作</template>
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row.no)"
              v-has="'article:edit'"
              >审核</el-button
            >
            <el-button
              size="small"
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row.no)"
              v-has="'article:del'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="dataTablePage">
      <el-pagination
        background
        :current-page="tableData.current"
        :page-size="tableData.size"
        :default-page-size="10"
        :page-sizes="[10, 20, 30, 40]"
        layout="sizes, prev, pager, next, jumper, ->, total"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-row>
  </div>

  <edit-form ref="editfrom" @getPage="getPage"></edit-form>
</template>
<style scoped lang="scss">
.el-col-lg-4-8 {
  width: 20%;
}
</style>
